#!/bin/bash
# MAESS智能体系统一键部署脚本（Linux版）
# 运行方式：chmod +x deploy_maess.sh && ./deploy_maess.sh

# 配色方案
RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

echo -e "${CYAN}============================================${NC}"
echo -e "${CYAN}MAESS智能体系统一键部署脚本${NC}"
echo -e "${CYAN}============================================${NC}"

# 检查bash版本
if [[ ${BASH_VERSION%%.*} -lt 4 ]]; then
    echo -e "${RED}错误：需要Bash 4.0或更高版本！${NC}"
    exit 1
fi

# 设置项目根目录
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
echo -e "${CYAN}项目根目录: ${PROJECT_ROOT}${NC}"

# 检查Python是否安装
echo -e "${CYAN}正在检查Python环境...${NC}"
if ! command -v python3 &> /dev/null; then
    echo -e "${RED}错误：未找到Python3，请先安装Python 3.8+！${NC}"
    echo -e "${YELLOW}Ubuntu/Debian: sudo apt-get install python3 python3-venv python3-pip${NC}"
    echo -e "${YELLOW}CentOS/RHEL: sudo yum install python3 python3-venv python3-pip${NC}"
    exit 1
fi

# 检查Python版本
PYTHON_VERSION=$(python3 --version 2>&1)
echo -e "${CYAN}当前Python版本: ${PYTHON_VERSION}${NC}"

# 创建虚拟环境
VENV_DIR="${PROJECT_ROOT}/.venv"
if [ ! -d "${VENV_DIR}" ]; then
    echo -e "${CYAN}正在创建虚拟环境...${NC}"
    python3 -m venv "${VENV_DIR}"
    if [ $? -ne 0 ]; then
        echo -e "${RED}错误：创建虚拟环境失败！${NC}"
        exit 1
    fi
    echo -e "${GREEN}虚拟环境创建成功！${NC}"
fi

# 激活虚拟环境
echo -e "${CYAN}正在激活虚拟环境...${NC}"
source "${VENV_DIR}/bin/activate"
if [ $? -ne 0 ]; then
    echo -e "${RED}错误：激活虚拟环境失败！${NC}"
    exit 1
fi
echo -e "${GREEN}虚拟环境激活成功！${NC}"

# 升级pip
echo -e "${CYAN}正在升级pip...${NC}"
pip install --upgrade pip -i https://mirrors.aliyun.com/pypi/simple/
if [ $? -ne 0 ]; then
    echo -e "${YELLOW}警告：pip升级失败，继续执行...${NC}"
fi

# 安装依赖（使用国内源）
REQUIREMENTS_FILE="${PROJECT_ROOT}/requirements_cn.txt"
if [ -f "${REQUIREMENTS_FILE}" ]; then
    echo -e "${CYAN}正在安装项目依赖（使用国内源）...${NC}"
    pip install -r "${REQUIREMENTS_FILE}" -i https://mirrors.aliyun.com/pypi/simple/
    if [ $? -ne 0 ]; then
        echo -e "${YELLOW}警告：部分依赖安装失败，可能需要手动处理！${NC}"
    else
        echo -e "${GREEN}依赖安装完成！${NC}"
    fi
fi

# 检查环境变量文件
ENV_FILE="${PROJECT_ROOT}/.env"
ENV_EXAMPLE_FILE="${PROJECT_ROOT}/.env.example"
if [ ! -f "${ENV_FILE}" ] && [ -f "${ENV_EXAMPLE_FILE}" ]; then
    echo -e "${CYAN}正在创建环境变量文件...${NC}"
    cp "${ENV_EXAMPLE_FILE}" "${ENV_FILE}"
    echo -e "${YELLOW}请编辑 .env 文件配置环境变量！${NC}"
fi

# 初始化数据库
echo -e "${CYAN}正在初始化数据库...${NC}"
INIT_SCRIPT="${PROJECT_ROOT}/init_mysql.py"
if [ -f "${INIT_SCRIPT}" ]; then
    python "${INIT_SCRIPT}"
    if [ $? -ne 0 ]; then
        echo -e "${YELLOW}警告：数据库初始化可能失败，请检查数据库配置！${NC}"
    else
        echo -e "${GREEN}数据库初始化完成！${NC}"
    fi
fi

# 检查Redis连接
echo -e "${CYAN}正在检查Redis连接...${NC}"
CHECK_REDIS_SCRIPT="${PROJECT_ROOT}/check_redis.py"
if [ -f "${CHECK_REDIS_SCRIPT}" ]; then
    python "${CHECK_REDIS_SCRIPT}"
    if [ $? -ne 0 ]; then
        echo -e "${YELLOW}警告：Redis连接失败，请确保Redis服务已启动！${NC}"
        echo -e "${YELLOW}Ubuntu/Debian: sudo systemctl start redis-server${NC}"
        echo -e "${YELLOW}CentOS/RHEL: sudo systemctl start redis${NC}"
    else
        echo -e "${GREEN}Redis连接成功！${NC}"
    fi
fi

# 启动Celery worker（后台运行）
echo -e "${CYAN}正在启动Celery worker...${NC}"
nohup celery -A celery_app worker --loglevel=info --detach
if [ $? -eq 0 ]; then
    echo -e "${GREEN}Celery worker启动成功！${NC}"
else
    echo -e "${YELLOW}警告：Celery worker启动失败！${NC}"
fi

# 创建启动服务脚本
START_SERVICES_SCRIPT="${PROJECT_ROOT}/start_services.sh"
cat > "${START_SERVICES_SCRIPT}" << 'EOF'
#!/bin/bash
# 启动所有服务的脚本
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${PROJECT_ROOT}/.venv/bin/activate"

# 启动API网关服务（前台运行）
echo "正在启动API网关服务..."
echo "服务启动后，请访问 http://localhost:8000/docs 查看API文档"
uvicorn api_gateway.app:app --reload --port 8000
EOF

chmod +x "${START_SERVICES_SCRIPT}"

# 创建启动前端服务脚本
FRONTEND_DIR="${PROJECT_ROOT}/maess-vue3-frontend"
if [ -d "${FRONTEND_DIR}" ]; then
    START_FRONTEND_SCRIPT="${PROJECT_ROOT}/start_frontend.sh"
    cat > "${START_FRONTEND_SCRIPT}" << 'EOF'
#!/bin/bash
# 启动前端服务的脚本
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "${PROJECT_ROOT}/maess-vue3-frontend"

# 启动前端服务（前台运行）
echo "正在启动前端服务..."
echo "前端服务启动后，请访问 http://localhost:3000"
npm run dev
EOF

    chmod +x "${START_FRONTEND_SCRIPT}"
    echo -e "${GREEN}前端启动脚本已创建: ${START_FRONTEND_SCRIPT}${NC}"
fi

echo -e "${CYAN}============================================${NC}"
echo -e "${GREEN}MAESS智能体系统部署完成！${NC}"
echo -e "${YELLOW}注意事项：${NC}"
echo -e "${YELLOW}1. 请确保MySQL和Redis服务已启动并配置正确${NC}"
echo -e "${YELLOW}2. 要启动API网关服务，请运行: ./start_services.sh${NC}"
if [ -f "${START_FRONTEND_SCRIPT}" ]; then
    echo -e "${YELLOW}3. 要启动前端服务，请在新终端中运行: ./start_frontend.sh${NC}"
fi
echo -e "${YELLOW}4. 如遇问题，请检查日志文件或重新运行此脚本${NC}"
echo -e "${CYAN}============================================${NC}"

# 询问是否现在启动服务
read -p "是否现在启动API网关服务？(y/n): " START_NOW
if [ "$START_NOW" = "y" ] || [ "$START_NOW" = "Y" ]; then
    echo -e "${CYAN}正在启动API网关服务...${NC}"
    exec "${START_SERVICES_SCRIPT}"
fi
